//
//  HCRefreshControl.swift
//  Hweibome
//
//  Created by apple on 15/12/12.
//  Copyright © 2015年 hechuan. All rights reserved.
//

import UIKit

private let RefreshControlH: CGFloat = 50
/**
 <#Description#>
 
 - Normal:     默认
 - Pulling:    下拉
 - Refreshing: 刷新
 */
enum HCRefreshControlState:Int {
    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
}
class HCRefreshControl: UIControl {
    var oldHcState: HCRefreshControlState = .Normal;
    
    var hcState : HCRefreshControlState = .Normal{
        didSet{
            switch hcState {
                
            case.Pulling:
                printLog("显示松开刷新,剪头转方向")
                messageLabel.text = "放开刷新"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case.Refreshing:
                printLog("加载中")
                messageLabel.text = "加载中..."
                arrowIcon.hidden = true
                indicator.startAnimating()
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var contentInset = self.scrollView!.contentInset
                    contentInset.top += RefreshControlH
                    self.scrollView?.contentInset = contentInset
                    
                })
                //发送指定事件
                sendActionsForControlEvents(.ValueChanged)
                
            case.Normal:
                printLog("Normal")
                messageLabel.text = "下拉刷新"
                arrowIcon.hidden = false
                indicator.stopAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                if oldHcState == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var contentInset = self.scrollView!.contentInset
                        contentInset.top -= RefreshControlH
                        self.scrollView?.contentInset = contentInset
                    })
                }
                
            }
            
            oldHcState = hcState
            
        }
     }
    
    var scrollView: UIScrollView?
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func endRefreshing(){
        hcState = .Normal
    }
    private func setupUI(){
        backgroundColor = UIColor.orangeColor()
        var frame = self.frame
        frame.size = CGSizeMake(SCREENW, RefreshControlH)
        frame.origin.y = -RefreshControlH
        self.frame = frame
        
        addSubview(arrowIcon)
        addSubview(messageLabel)
        addSubview(indicator)
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-35)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(arrowIcon)
            make.leading.equalTo(arrowIcon.snp_trailing).offset(5)
        }
        indicator.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
        
    }
    
    
    override func willMoveToSuperview(newSuperview: UIView?) {
      //  printLog(newSuperview)
        if let scrollView = newSuperview as? UIScrollView {
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: [NSKeyValueObservingOptions.New], context: nil)
            self.scrollView = scrollView
            
            var frame = self.frame
            frame.size.width = scrollView.frame.width
            self.frame = frame
        }
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        let contentOffsetY = scrollView?.contentOffset.y
        
        let contentInsetTop = scrollView?.contentInset.top ?? 0
        
        let conditionValue = -contentInsetTop - RefreshControlH
        
        if scrollView!.dragging {
            if hcState == .Normal && contentOffsetY < conditionValue {
                hcState = .Pulling
            } else if hcState == .Pulling && contentOffsetY >= conditionValue {
                hcState = .Normal
            }
        }else {
            if hcState == .Pulling {
                hcState = .Refreshing
            }
        }
    }
    
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
     //MARK: - 懒加载空间
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var messageLabel : UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        label.text = "下拉刷新"
        return label
    }()
    
    private lazy var indicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray )
    
}















